package com.github.McPlugin.util.Task;

import com.github.McPlugin.dao.MySQLManager;
import com.github.McPlugin.main;
import com.google.gson.Gson;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class TasksTool {
    public static List<Task> list_DailyTask = null;
    public static List<PlayerTasks> list_tasks = null;
    public static List<PlayerTasks> list_finished = null;

    public static void init() {

//        new BukkitRunnable(){
//            @Override
//            public void run(){
////                list_tasks = fromDB(ListType.UNFINISHED_LIST);
////                list_finished = fromDB(ListType.FINISHED_LIST);
////                list_DailyTask = fromDB(ListType.DAILYTASK_LIST);

//
//
//            }
//        }.runTaskAsynchronously(main.plugin);
        list_tasks = new ArrayList<>();
        list_finished = new ArrayList<>();
        list_DailyTask = new ArrayList<>();
//
//        Task task1 = new Task();
//        task1.setID(10001);
//        task1.setTaskName("助人为乐");
//        task1.setTaskType("Mixed");
//        task1.setEntityTasks("PIG", 10);
//        task1.setBlockTask("Block_build", 6);
//        task1.setTaskDescription("夜深人静，淘气的小猪们偷偷跑出了农场，村民们很是着急，快去给小猪们一点惩罚吧,建造帮村民建造一下村庄吧");
//
//        Task task2 = new Task();
//        task2.setID(10002);
//        task2.setTaskName("家园重建");
//        task2.setTaskType("Block");
//        task2.setBlockTask("Block_build", 10);
//        task2.setTaskDescription("狂风呼啸，摧毁了村民们的家园，快去帮他们重建一下吧");
//
//        Task task3 = new Task();
//        task3.setID(10003);
//        task3.setTaskName("战斗吧！");
//        task3.setTaskType("Entity");
//        task3.setEntityTasks("PIG", 10);
//        task3.setTaskDescription("猪肉价格大涨，村民们举办了活动，杀死小猪会有神秘奖励哦");
//
//        Task task4 = new Task();
//        task4.setID(10004);
//        task4.setTaskName("占山为王");
//        task4.setTaskType("Block");
//        task4.setBlockTask("Block_build", 20);
//        task4.setTaskDescription("在这个世界上，谁占领谁拥有，快去新建一个建筑，让他们知道谁才是这里的王");
//
//        Task task5 = new Task();
//        task5.setID(10005);
//        task5.setTaskName("僵尸猎手");
//        task5.setTaskType("Entity");
//        task5.setBlockTask("ZOMBIE", 3);
//        task5.setTaskDescription("僵尸怒吼，影响了夜间人们的安全，快去杀死僵尸，保护村民安全吧");
//
//        Task task6 = new Task();
//        task6.setID(10005);
//        task6.setTaskName("破坏能手");
//        task6.setTaskType("Entity");
//        task6.setBlockTask("Block_break", 10);
//        task6.setTaskDescription("愚蠢的人们还以为占山即可为王，是时候让他们尝尝我们的厉害");
//
//        Gson g =new Gson();
//        MySQLManager.get().insertTasks(task1.getID(),task1.getTaskName(),task1.getTaskType(),task1.getTaskDescription(),g.toJson(task1.getTasks()));
//        MySQLManager.get().insertTasks(task2.getID(),task2.getTaskName(),task2.getTaskType(),task2.getTaskDescription(),g.toJson(task2.getTasks()));
//        MySQLManager.get().insertTasks(task3.getID(),task3.getTaskName(),task3.getTaskType(),task3.getTaskDescription(),g.toJson(task3.getTasks()));
//        MySQLManager.get().insertTasks(task4.getID(),task4.getTaskName(),task4.getTaskType(),task4.getTaskDescription(),g.toJson(task4.getTasks()));
//        MySQLManager.get().insertTasks(task5.getID(),task5.getTaskName(),task5.getTaskType(),task5.getTaskDescription(),g.toJson(task5.getTasks()));
//        MySQLManager.get().insertTasks(task6.getID(),task6.getTaskName(),task6.getTaskType(),task6.getTaskDescription(),g.toJson(task6.getTasks()));

        list_DailyTask = (List<Task>)fromDB(ListType.DAILYTASK_LIST);
        list_tasks = (List<PlayerTasks>)fromDB(ListType.UNFINISHED_LIST);
        list_finished = (List<PlayerTasks>)fromDB(ListType.FINISHED_LIST);

//        TasksTool.list_DailyTask.add(task1);
//        TasksTool.list_DailyTask.add(task2);
//        TasksTool.list_DailyTask.add(task3);
//        TasksTool.list_DailyTask.add(task4);
//        TasksTool.list_DailyTask.add(task5);
        //TasksTool.list_DailyTask.add(task6);

    }

    /**
     * 传入玩家对象和任务对象，完成任务添加
     *
     * @param player
     * @param task
     */
    public static void addPlayerTasks(Player player, Task task) {
        if (list_tasks.size() > 0) {
            boolean flag = false;
            for (PlayerTasks t : list_tasks) {
                if (t.getPlayer().getUniqueId() != player.getUniqueId())
                    continue;
                else {
                    Task nt = new Task();
                    nt.setID(task.getID());
                    nt.setTaskName(task.getTaskName());
                    nt.setTaskType(task.getTaskType());
                    nt.setTasks(task.getTasks());
                    nt.setTaskDescription(nt.getTaskDescription());
                    t.addTasktoList(nt);
                    flag = true;
                    player.sendMessage(task.getTaskName() + "任务已领取");
                    break;
                }
            }
            if (!flag) {
                PlayerTasks playerTasks = new PlayerTasks();
                playerTasks.setPlayer(player);
                Task nt = new Task();
                nt.setID(task.getID());
                nt.setTaskName(task.getTaskName());
                nt.setTaskType(task.getTaskType());
                nt.setTasks(task.getTasks());
                nt.setTaskDescription(nt.getTaskDescription());
                playerTasks.addTasktoList(nt);
                list_tasks.add(playerTasks);
                player.sendMessage(task.getTaskName() + "任务已领取");
            }
        } else {
            PlayerTasks playerTasks = new PlayerTasks();
            playerTasks.setPlayer(player);
            Task nt = new Task();
            nt.setID(task.getID());
            nt.setTaskName(task.getTaskName());
            nt.setTaskType(task.getTaskType());
            nt.setTasks(task.getTasks());
            nt.setTaskDescription(nt.getTaskDescription());
            playerTasks.addTasktoList(nt);
            list_tasks.add(playerTasks);
            player.sendMessage(task.getTaskName() + "任务已领取");
        }
    }

    /**
     * 传入玩家对象和任务对象，完成任务添加
     *
     * @param player
     * @param task
     */
    public static void addFinishedTasks(Player player, Task task) {
        if (list_finished.size() > 0) {
            boolean flag = false;
            for (PlayerTasks t : list_finished) {
                if (t.getPlayer().getUniqueId() != player.getUniqueId())
                    continue;
                else {
                    t.addTasktoList(task);
                    flag = true;
                    player.sendMessage(task.getTaskName() + "该任务已完成");
                    break;
                }
            }
            if (!flag) {
                PlayerTasks playerTasks = new PlayerTasks();
                playerTasks.setPlayer(player);
                playerTasks.addTasktoList(task);
                list_finished.add(playerTasks);
                player.sendMessage(task.getTaskName() + "该任务已完成");
            }
        } else {
            PlayerTasks playerTasks = new PlayerTasks();
            playerTasks.setPlayer(player);
            playerTasks.addTasktoList(task);
            list_finished.add(playerTasks);
            player.sendMessage(task.getTaskName() + "该任务已完成");
        }
    }

    /**
     * 游戏中与任务有关的事件处理
     *
     * @param events
     */
    public static void TaskEvent(Event events) {
        if (events instanceof BlockBreakEvent) {
            BlockBreakEvent event = (BlockBreakEvent) events;
            Player player = event.getPlayer();
            Iterator<PlayerTasks> it_pt = TasksTool.list_tasks.iterator();
            while (it_pt.hasNext()) {
                PlayerTasks playerTasks = it_pt.next();
                List<Task> list_task = playerTasks.getList_task();
                if (list_task.size() > 0) {
                    boolean flag_break = false;  //false表示没有计数过
                    Iterator<Task> it_task = list_task.iterator();
                    while (it_task.hasNext()) {
                        Task task = it_task.next();
                        if (!task.isFinished()) {
                            boolean flag_finished = true;//任务是否全部完成，true表示该任务全部完成
                            Iterator<Object> it_ob = task.getTasks().keySet().iterator();
                            while (it_ob.hasNext()) {
                                Object key = it_ob.next();
                                if (key instanceof String) {
                                    if (key.toString().equalsIgnoreCase("Block_break")) {
                                        if (!flag_break) {
                                            if ((int) task.getTasks().get(key) == 1) {
                                                task.getTasks().put(key, (int) task.getTasks().get(key) - 1);
                                                event.getPlayer().sendMessage(task.getTaskName() + "破坏任务完成");
                                            } else if ((int) task.getTasks().get(key) > 1) {
                                                task.getTasks().put(key, (int) task.getTasks().get(key) - 1);
                                                event.getPlayer().sendMessage(task.getTaskName() + "任务要求的" + key + "数目减一，还有" + (int) task.getTasks().get(key) + "个方块需要破坏");
                                            } else {
                                                continue;
                                            }
                                            flag_break = true;
                                        }
                                    }
                                }
                                if ((int) task.getTasks().get(key) != 0)
                                    flag_finished = false;
                            }
                            if (flag_finished) {
                                task.setFinished();
                                TasksTool.addFinishedTasks(player, task);

                                player.sendMessage(task.getTaskName() + "任务已完成");
                                it_task.remove();
                                player.sendMessage(player.getName() + "的任务还有" + String.valueOf(list_task.size()) + "个");
                                player.sendMessage(player.getName() + "在list_finished的任务已有" + String.valueOf(list_finished.get(0).getList_task().size()) + "个");
                            }
                        }

                    }
                }
            }


        } else if (events instanceof BlockPlaceEvent) {
            BlockPlaceEvent event = (BlockPlaceEvent) events;
            Player player = event.getPlayer();
            Iterator<PlayerTasks> it_pt = TasksTool.list_tasks.iterator();
            while (it_pt.hasNext()) {
                PlayerTasks playerTasks = it_pt.next();
                List<Task> list_task = playerTasks.getList_task();
                if (list_task.size() > 0) {
                    boolean flag_build = false;  //false表示没有计数过
                    Iterator<Task> it_task = list_task.iterator();
                    while (it_task.hasNext()) {
                        Task task = it_task.next();
                        if (!task.isFinished()) {
                            boolean flag_finished = true;//任务是否全部完成，true表示该任务全部完成
                            Iterator<Object> it_ob = task.getTasks().keySet().iterator();
                            while (it_ob.hasNext()) {
                                Object key = it_ob.next();
                                if (key instanceof String) {
                                    if (key.toString().equalsIgnoreCase("Block_build")) {
                                        if (!flag_build) {
                                            if ((int) task.getTasks().get(key) == 1) {
                                                task.getTasks().put(key, (int) task.getTasks().get(key) - 1);
                                                event.getPlayer().sendMessage(task.getTaskName() + "建造任务完成");
                                            } else if ((int) task.getTasks().get(key) > 1) {
                                                task.getTasks().put(key, (int) task.getTasks().get(key) - 1);
                                                event.getPlayer().sendMessage(task.getTaskName() + "任务要求的" + key + "数目减一，还有" + (int) task.getTasks().get(key) + "个方块需要破坏");
                                            } else {
                                                continue;
                                            }
                                            flag_build = true;
                                        }
                                    }
                                }
                                if ((int) task.getTasks().get(key) != 0)
                                    flag_finished = false;
                            }
                            if (flag_finished) {
                                task.setFinished();
                                TasksTool.addFinishedTasks(player, task);

                                player.sendMessage(task.getTaskName() + "任务已完成");
                                it_task.remove();
                                player.sendMessage(player.getName() + "的任务还有" + String.valueOf(list_task.size()) + "个");
                                player.sendMessage(player.getName() + "在list_finished的任务已有" + String.valueOf(list_finished.get(0).getList_task().size()) + "个");
                            }
                        }

                    }
                }
            }

        } else if (events instanceof EntityDamageByEntityEvent) {
            EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) events;
            Entity damager = event.getDamager();
            Player player = (Player) damager;
            Iterator<PlayerTasks> it_pt = TasksTool.list_tasks.iterator();
            while (it_pt.hasNext()) {
                PlayerTasks playerTasks = it_pt.next();
                List<Task> list_task = playerTasks.getList_task();
                if (list_task.size() > 0) {
                    boolean flag_entity = false;  //false表示没有计数过
                    Iterator<Task> it_task = list_task.iterator();
                    while (it_task.hasNext()) {
                        Task task = it_task.next();
                        if (!task.isFinished()) {
                            boolean flag_finished = true;//任务是否全部完成，true表示该任务全部完成
                            Iterator<Object> it_ob = task.getTasks().keySet().iterator();
                            while (it_ob.hasNext()) {
                                Object key = it_ob.next();
                                if (key instanceof EntityType) {
                                    if (event.getEntity().getType() == key) {
                                        if (!flag_entity) {
                                            if ((int) task.getTasks().get(key) == 1) {
                                                task.getTasks().put(event.getEntity().getType(), (int) task.getTasks().get(key) - 1);
                                                event.getDamager().sendMessage(task.getTaskName() + "的击杀任务完成");
                                                //task.setFinished();
                                            } else if ((int) task.getTasks().get(key) > 1) {
                                                task.getTasks().put(event.getEntity().getType(), (int) task.getTasks().get(key) - 1);
                                                event.getDamager().sendMessage(task.getTaskName() + "任务要求的" + key + "数目减一，还有" + (int) task.getTasks().get(key) + "只");
                                            } else {
                                                continue;
                                            }
                                            flag_entity = true;
                                        }

                                    }
                                }
                                if ((int) task.getTasks().get(key) != 0)
                                    flag_finished = false;
                            }
                            if (flag_finished) {
                                task.setFinished();
                                TasksTool.addFinishedTasks(player, task);

                                player.sendMessage(task.getTaskName() + "任务已完成");
                                it_task.remove();
                                player.sendMessage(player.getName() + "的任务还有" + String.valueOf(list_task.size()) + "个");
                                player.sendMessage(player.getName() + "在list_finished的任务已有" + String.valueOf(list_finished.get(0).getList_task().size()) + "个");
                            }
                        }

                    }
                }
            }
        }

    }

    /**
     * 任务序列化字符串储存到数据库
     *
     * @param l
     * @param lt
     */
    public static void toDB(List l, ListType lt) {
        Gson g = new Gson();
        String data = g.toJson(l);
        Calendar cal = Calendar.getInstance();
        Date date = new Date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
        //TODO 完成任务序列化字符串储存到数据库的操作
        if (lt == ListType.FINISHED_LIST) {
            MySQLManager.get().updateFinished(date,data);
        } else if (lt == ListType.UNFINISHED_LIST) {
            MySQLManager.get().updateUnfinished(date,data);
        }else if(lt == ListType.DAILYTASK_LIST){
            MySQLManager.get().updateDaily(date,data);
        }


    }

    /**
     * 每天随机刷取任务
     */
    public static List getDailyTask() {
        List list_task = new ArrayList();

        int id = main.plugin.getConfig().getInt("tasks.task0.id");
        String name = main.plugin.getConfig().getString("tasks.task0.name");
        String type = main.plugin.getConfig().getString("tasks.task0.type");
        String description = main.plugin.getConfig().getString("tasks.task0.description");
        String re0_type = main.plugin.getConfig().getString("tasks.task0.request.request0.type");
        int re0_num = main.plugin.getConfig().getInt("tasks.task0.request.request0.num");
        String re1_type = main.plugin.getConfig().getString("tasks.task0.request.request1.type");
        int re1_num = main.plugin.getConfig().getInt("tasks.task0.request.request1.num");

        /*player.sendMessage("id:" + id);
        player.sendMessage("name:" + name);
        player.sendMessage("type:" + type);
        player.sendMessage("description:" + description);
        player.sendMessage("re0:" + re0_type + "  " + re0_num);
        player.sendMessage("re1:" + re1_type + "  " + re1_num);*/

        Task task1 = new Task();
        Task task2 = new Task();
        Task task3 = new Task();
        Task task4 = new Task();
        Task task5 = new Task();
        Task task6 = new Task();

        task1.setID(id);
        task1.setTaskName(name);
        task1.setTaskType(type);
        task1.setTaskDescription(description);
        task1.setEntityTasks(re0_type, re0_num);
        task1.setBlockTask(re1_type, re1_num);

        task2.setID(10002);
        task2.setEntityTasks("PIG", 2);
        task2.setTaskDescription("任务2");
        task2.setTaskName("Task2");

        task3.setID(10003);
        task3.setEntityTasks("PIG", 3);
        task3.setTaskDescription("任务3");
        task3.setTaskName("Task3");

        task4.setID(10004);
        task4.setEntityTasks("PIG", 4);
        task4.setTaskDescription("任务4");
        task4.setTaskName("Task4");

        task5.setID(10005);
        task5.setEntityTasks("PIG", 5);
        task5.setTaskDescription("任务5");
        task5.setTaskName("Task5");

        task6.setID(10006);
        task6.setEntityTasks("PIG", 6);
        task6.setTaskDescription("任务6");
        task6.setTaskName("Task6");

        list_task.add(task1);
        list_task.add(task2);
        list_task.add(task3);
        list_task.add(task4);
        list_task.add(task5);
        list_task.add(task6);


        return list_task;


    }

    /**
     * 任务从数据库获得序列化字符串
     *
     * @param lt
     * @return
     */
    public static List fromDB(ListType lt) {
        Gson g = new Gson();

        //TODO 完成任务从数据库获得序列化字符串操作
        if (lt == ListType.FINISHED_LIST) {
            //获得当日所有玩家未完成的任务列表
            Calendar cal = Calendar.getInstance();
            Date date = new Date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));


            if (!MySQLManager.get().hasFinished(date)) {
                list_finished = new ArrayList<>();
                MySQLManager.get().insertFinishedtask(date, g.toJson(list_finished));
                main.plugin.getLogger().info("已完成任务初始化完成");
                return null;
            } else {
                String s = MySQLManager.get().selectFinishedtask(date);
                main.plugin.getLogger().info("已完成任务初始化完成");
                return g.fromJson(s, List.class);
            }


        } else if (lt == ListType.UNFINISHED_LIST) {
            //获得当日所有玩家已完成的任务列表
            Calendar cal = Calendar.getInstance();
            Date date = new Date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));

            if (!MySQLManager.get().hasUnfinished(date)) {
                list_tasks = new ArrayList<>();
                MySQLManager.get().insertUnfinishedtask(date, g.toJson(list_tasks));
                main.plugin.getLogger().info("未完成任务初始化完成");
                return null;
            } else {
                String s = MySQLManager.get().selectUnfinishedtask(date);
                main.plugin.getLogger().info("未完成任务初始化完成");
                return g.fromJson(s, List.class);
            }

        } else if (lt == ListType.DAILYTASK_LIST) {
            try {
                Calendar cal = Calendar.getInstance();
                Date date = new Date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
                //String s = MySQLManager.get().selectDailytask(date);
                if (!MySQLManager.get().hasDaily(date)) {
                    list_DailyTask = new ArrayList<>();
                    List<Task> list_t = MySQLManager.get().selectTasks();
                    Iterator<Task> it_t = list_t.iterator();
                    int count = 0;
                    while(it_t.hasNext()){
                        if(count<5){
                            double random = Math.random();
                            if(random<0.5){
                                list_DailyTask.add(it_t.next());
                                count++;
                            }else{
                                continue;
                            }
                        }else break;
                    }
                    MySQLManager.get().insertDailytask(date,g.toJson(list_DailyTask));

                } else {
                    list_DailyTask = (List<Task>) g.fromJson(MySQLManager.get().selectDailytask(date), List.class);
                    main.plugin.getLogger().info("每日任务初始化完成");
                }
            } catch (Exception throwables) {
                throwables.printStackTrace();
            }

        }
        return null;
    }


}
